# ！/usr/bin/env python
# -*- coding = utf-8 -*-
# ================================================
# @Time  :2021/8/5 17:33
# @Author:tyh
# @File  :task.py
# @Phone :13926528314
# ================================================
from flask import request
from flask_restful import Resource

from models.task import Task
from server import app, db
from utils.execute_tools import ExcuteTools


class TaskServer(Resource):
    """
    测试任务服务
    """
    def get(self):
        app.logger.info("查找所有用例")
        task_data = Task.query.all()
        # data = [{"id":i.id, "nodeid":i.nodeid, "remark":i.remark}for i in case_data]
        data = [i.as_dict() for i in task_data]
        return {"error": 0, "msg": {"data": data}}

    def post(self):
        """
        1.调用jenkins执行用例
        2.执行用例之后
        :return:
        """
        data = request.json
        nodeid = [i["nodeid"] for i in data]
        nodeid = " ".join(nodeid)
        app.logger.info(f"执行用例nodeid={nodeid}")
        report_dir = ExcuteTools().invoke(nodeid)
        app.logger.info(f"执行用例,返回报告为:{report_dir}")
        task = Task(remark=nodeid, report=report_dir)
        db.session.add(task)
        db.session.commit()
        db.session.close()
        return {"error": 0, "msg": "post success"}